package com.yjj.springboot3.controller;

import com.yjj.springboot3.common.BaseResponse;
import com.yjj.springboot3.common.ErrorCode;
import com.yjj.springboot3.common.ResultUtils;
import com.yjj.springboot3.config.FileConfig;
import com.yjj.springboot3.exception.BusinessException;
import com.yjj.springboot3.model.entity.User;
import com.yjj.springboot3.service.UserService;
import com.yjj.springboot3.utils.FileUploadUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件接口
 *
 * @author yjj
 */
@RestController
@RequestMapping("/file")
@Slf4j

public class FileController {

    @Resource
    private UserService userService;

    @Resource
    private FileUploadUtils fileUploadUtils;

    @Resource
    private FileConfig fileConfig;

    /**
     * 文件上传
     *
     * @param file    上传的文件
     * @param request 请求
     * @return 上传结果
     */
    @PostMapping("/upload")
    @Operation(summary = "文件上传", description = "上传单个文件")
    public BaseResponse<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file,
                                                        HttpServletRequest request) {
        try {
            // 验证用户登录
            User loginUser = userService.getLoginUser(request);
            if (loginUser == null) {
                throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
            }

            // 上传并返回新文件名称
            String fileName = fileUploadUtils.upload(file);

            Map<String, Object> result = new HashMap<>();
            result.put("fileName", fileName);
            result.put("originalFilename", file.getOriginalFilename());
            result.put("url", fileName);
            result.put("size", file.getSize());

            return ResultUtils.success(result);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 批量文件上传
     *
     * @param files   上传的文件列表
     * @param request 请求
     * @return 上传结果
     */
    @PostMapping("/uploads")
    @Operation(summary = "批量文件上传", description = "同时上传多个文件")
    public BaseResponse<Map<String, Object>> uploadFiles(@RequestParam("files") List<MultipartFile> files,
                                                         HttpServletRequest request) {
        try {
            // 验证用户登录
            User loginUser = userService.getLoginUser(request);
            if (loginUser == null) {
                throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
            }
            List<String> fileNames = new ArrayList<>();
            List<String> originalFilenames = new ArrayList<>();
            List<String> urls = new ArrayList<>();
            List<Long> sizes = new ArrayList<>();

            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = fileUploadUtils.upload(file);
                fileNames.add(fileName);
                originalFilenames.add(file.getOriginalFilename());
                urls.add(fileName);
                sizes.add(file.getSize());
            }
            Map<String, Object> result = new HashMap<>();
            result.put("fileNames", fileNames);
            result.put("originalFilenames", originalFilenames);
            result.put("urls", urls);
            result.put("sizes", sizes);

            return ResultUtils.success(result);
        } catch (Exception e) {
            log.error("批量文件上传失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "批量文件上传失败：" + e.getMessage());
        }
    }
    /**
     * 头像上传
     *
     * @param file    上传的头像文件
     * @param request 请求
     * @return 上传结果
     */
    @PostMapping("/avatar")
    @Operation(summary = "头像上传", description = "上传用户头像（仅支持图片格式）")
    public BaseResponse<Map<String, Object>> uploadAvatar(@RequestParam("file") MultipartFile file,
                                                          HttpServletRequest request) {
        try {
            // 验证用户登录
            User loginUser = userService.getLoginUser(request);
            if (loginUser == null) {
                throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
            }
            // 上传头像（只允许图片格式）
            String fileName = fileUploadUtils.upload(fileConfig.getAvatarPath(), file, FileUploadUtils.IMAGE_EXTENSION);
            Map<String, Object> result = new HashMap<>();
            result.put("fileName", fileName);
            result.put("originalFilename", file.getOriginalFilename());
            result.put("url", fileName);
            result.put("size", file.getSize());
            return ResultUtils.success(result);
        } catch (Exception e) {
            log.error("头像上传失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "头像上传失败：" + e.getMessage());
        }
    }
}
